package net.araim.bbingo.activity;

import java.util.HashMap;

import net.araim.bbingo.R;
import net.araim.bbingo.adapters.EditTextsViewBinder;
import net.araim.bbingo.db.BingoDB;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class EditTextsActivity extends Activity {

	private static int MENU_RESET = 1;

	private BingoDB bdb = null;
	private ListView lv = null;
	private SimpleCursorAdapter sca = null;
	private final Handler mHandler = new Handler();
	private Cursor c = null;

	// Create runnable for posting
	private final Runnable notifyList = new Runnable() {
		public void run() {
			c.requery();
			EditTextsActivity.this.sca.notifyDataSetChanged();
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(c != null){
			try{
				c.close();
			}catch (Exception e) {
				Log.e(CorporateBingo.LOGTAG, "Error closing localy managed cursor: " + e.toString());
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edittexts);
		lv = (ListView) findViewById(R.id.TextsList);

		bdb = new BingoDB(this);
		c = bdb.getAllTextsCursor();
		startManagingCursor(c);
		sca = new SimpleCursorAdapter(this, R.layout.textlistitem, c, new String[] { "name", "_id" }, new int[] { R.id.TextListItemId,
				R.id.DeleteSelectedToggle });

		final TextsDeleter td = new TextsDeleter();
		sca.setViewBinder(new EditTextsViewBinder(td));
		lv.setAdapter(sca);
		final Button addButton = (Button) findViewById(R.id.AddTextsButton);

		final Button deleteButton = (Button) EditTextsActivity.this.findViewById(R.id.DeleteTextsButton);
		deleteButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				bdb.deleteTexts(td.getTextsToDelete());
				mHandler.post(notifyList);
				td.clear();
				deleteButton.setText(R.string.Delete);
				deleteButton.setEnabled(false);
			}
		});
		final TextView tv = (TextView) findViewById(R.id.NewBoardText);
		tv.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (tv.getText() == null || tv.getText().toString().trim().equals("")) {
					addButton.setEnabled(false);
				} else {
					addButton.setEnabled(true);
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		addButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				bdb.addText(tv.getText().toString());
				tv.setText("");
				mHandler.post(notifyList);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO change to IDS, move texts to strings
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_RESET, 0, R.string.ResetTexts).setIcon(android.R.drawable.ic_menu_manage);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		if (item.getItemId() == MENU_RESET) {
			new AlertDialog.Builder(this).setTitle(R.string.FactoryResetConfirmTitle).setMessage(R.string.FactoryResetConfirmMessage)
			.setPositiveButton(R.string.Yes, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					bdb.resetFactorySettings();
					mHandler.post(notifyList);
				}
			}).setNegativeButton(R.string.No, null).show();
			return true;
		}
		return false;
	}

	public class TextsDeleter {
		private HashMap<Integer, View> toDelete = new HashMap<Integer, View>();

		public TextsDeleter() {

		}

		public void clear() {
			toDelete.clear();
		}

		public Integer[] getTextsToDelete() {
			return toDelete.keySet().toArray(new Integer[0]);
		}

		public View[] getViewsToRemove() {
			return toDelete.values().toArray(new View[0]);
		}

		public void registerDeletion(View v) {
			Integer i = (Integer) v.findViewById(R.id.TextListItemId).getTag();
			toDelete.put(i, v);
			updateActivity();
		}

		public void unRegisterDeletion(View v) {
			Integer i = (Integer) v.findViewById(R.id.TextListItemId).getTag();
			toDelete.remove(i);
			updateActivity();
		}

		public void unRegisterDeletion(int i) {
			toDelete.remove(i);
			updateActivity();
		}

		private void updateActivity() {
			Button b = (Button) EditTextsActivity.this.findViewById(R.id.DeleteTextsButton);
			String d = getResources().getString(R.string.Delete);
			if (toDelete.size() == 0) {
				b.setEnabled(false);
				b.setText(d);
			} else {
				b.setEnabled(true);
				b.setText(d + "(" + toDelete.size() + ")");
			}
		}

		public boolean isRegisteredToDelete(Integer tag) {
			return toDelete.containsKey(tag);
		}

	}
}
